package com.konjac.controller;

import com.konjac.dto.TotalAndSortDto;
import com.konjac.pojo.AddOrder;
import com.konjac.pojo.ServiceState;
import com.konjac.service.impl.AddOrderServiceImpl;
import com.konjac.service.impl.TotalServiceImpl;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class AdminController {

    @RequestMapping("/addOrder")
    @ResponseBody
    public ServiceState addOrder(@RequestBody AddOrder addOrder) {
        ServiceState serviceState = new ServiceState();
        AddOrderServiceImpl addOrderService = new AddOrderServiceImpl();
        try {
            serviceState  = addOrderService.AddOrder(addOrder.getBookId(),addOrder.getSupplierId(),addOrder.getAddNumber());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return serviceState;
    }

    @RequestMapping("/totalPrice")
    @ResponseBody
    public List<TotalAndSortDto> totalPrice() {
        TotalServiceImpl totalService = new TotalServiceImpl();
        Map<String, Double> priceMap = null;
        List<TotalAndSortDto> totalAndSortDtoList = new ArrayList<>();
        try {
            priceMap = totalService.sortByPrice();
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (Map.Entry<String, Double> entry : priceMap.entrySet()) {
            //System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
            TotalAndSortDto totalAndSortDto = new TotalAndSortDto();
            totalAndSortDto.setMonth(entry.getKey());
            totalAndSortDto.setTotalPrice(entry.getValue());
            totalAndSortDtoList.add(totalAndSortDto);
        }
        return totalAndSortDtoList;
    }

    @RequestMapping("/totalNumber")
    @ResponseBody
    public List<TotalAndSortDto> totalNumber() {
        TotalServiceImpl totalService = new TotalServiceImpl();
        Map<String, Integer> numberMap = null;
        List<TotalAndSortDto> totalAndSortDtoList = new ArrayList<>();
        try {
            numberMap = totalService.sortByNumber();
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (Map.Entry<String, Integer> entry : numberMap.entrySet()) {
            //System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
            TotalAndSortDto totalAndSortDto = new TotalAndSortDto();
            totalAndSortDto.setMonth(entry.getKey());
            totalAndSortDto.setTotalNumber(entry.getValue());
            totalAndSortDtoList.add(totalAndSortDto);
        }
        return totalAndSortDtoList;
    }

}
